package com.lineage.server;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_PacketBoxGree;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class BroadcastController implements Runnable {
  private static final Log _log = LogFactory.getLog(BroadcastController.class);
  
  private static BroadcastController _instance;
  
  private static boolean _isStop;
  
  private static final int MAX_MSG_SIZE = 20;
  
  private static final Queue<String> _msgQueue = new ConcurrentLinkedQueue<>();
  
  private ScheduledFuture<?> _timer;
  
  public static BroadcastController getInstance() {
    if (_instance == null)
      _instance = new BroadcastController(); 
    return _instance;
  }
  
  public final int getMsgSize() {
    return _msgQueue.size();
  }
  
  public final boolean requestWork(String data) {
    return (_msgQueue.size() < 20 && _msgQueue.offer(data));
  }
  
  public final boolean isStop() {
    return _isStop;
  }
  
  public final void setStop(boolean stop) {
    _isStop = stop;
  }
  
  public void run() {
    try {
      if (_isStop)
        return; 
      if (_msgQueue.isEmpty())
        return; 
      Collection<L1PcInstance> all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      String message = _msgQueue.poll();
      S_ServerMessage s_ServerMessage = new S_ServerMessage(message);
      S_PacketBoxGree s_PacketBoxGree = new S_PacketBoxGree(2, "\\f=" + message);
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance pc = iter.next();
        if (check(pc)) {
          pc.sendPackets((ServerBasePacket)s_ServerMessage);
          pc.sendPackets((ServerBasePacket)s_PacketBoxGree);
        } 
        Thread.sleep(1L);
      } 
    } catch (Exception e) {
      _log.error("广播系统时间轴异常重启");
      GeneralThreadPool.get().cancel(this._timer, false);
      (_instance = new BroadcastController()).start();
    } 
  }
  
  private static boolean check(L1PcInstance tgpc) {
    try {
      if (tgpc == null)
        return false; 
      if (tgpc.getOnlineStatus() == 0)
        return false; 
      if (tgpc.getNetConnection() == null)
        return false; 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
      return false;
    } 
    return true;
  }
  
  public final void start() {
    int timeMillis = 3000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 3000L, 3000L);
  }
}
